<script lang="ts">
//使用<keep-alive></keep-alive>缓存路由必须显式的声明name
export default {
  name: "role",
};
</script>

<script setup lang="ts">
import { reactive, ref, onMounted, nextTick } from "vue";
import {
  Search,
  Plus,
  Refresh,
  Setting,
  EditPen,
  Delete,
  Finished,
} from "@element-plus/icons-vue";
import {
  get_roleinfo,
  insert_roleinfo,
  update_roleinfo,
  delete_roleinfo,
  get_rightinfo,
  set_right,
} from "../../request/api";
import { ElMessage } from "element-plus";
import type { ElForm, ElTree } from "element-plus";
//搜索表单
const roleseachform = reactive({
  name: "",
});
//角色的表格数据
const roletable = ref([]);
//表格的加载开关
const loading = ref(false);
//当前页
const currentPage = ref(1);
//总页数
const total = ref();
//每页显示条目个数
const pageSize = ref(10);
//角色新增和修改的弹出框
const dialogrole = ref(false);
//分配权限的弹出框
const dianlogsetrole = ref(false);
//角色新增和修改的表单
const roleform = reactive({
  role_name: "",
  role_remarks: "",
});
//模态框的类型0是新增1是修改
const dialogtype = ref(0);
//要修改的角色的角色id
const roleid = ref(0);
//switch的加载开关
// const loadingswitch = ref(false);
//分配权限的loading
const treeloading = ref(false);
//所有权限树
const rigthtred = ref([]);

//配置默认props项
const defaultProps = {
  children: "child",
  label: "right_name",
};

//角色新增和修改的表单效验规则
type FormInstance = InstanceType<typeof ElForm>;
const roleformref = ref<FormInstance>();
//树的ref
const treeRef = ref<InstanceType<typeof ElTree>>();

const roleformrule = reactive({
  role_name: [
    {
      required: true,
      message: "角色名不能为空",
      trigger: "blur",
    },
    {
      min: 1,
      max: 11,
      message: "请输入1到10个字符",
      trigger: "blur",
    },
  ],
});
//刷新数据
const refreshtable = async (currentPage, pagsize) => {
  loading.value = true;
  const { data } = await get_roleinfo(currentPage, pagsize);
  loading.value = false;
  if (data.code == 200) {
    roletable.value = data.data.data;
    total.value = data.data.total;
  } else {
    ElMessage.error(data.msg);
  }
};
//请求数据
loading.value = true;
const { data } = await get_roleinfo(1, pageSize.value);
loading.value = false;
if (data.code == 200) {
  roletable.value = data.data.data;
  total.value = data.data.total;
  console.log(roletable.value);
} else {
  ElMessage.error(data.msg);
}
//监听current-page事件
const handleCurrentChange = async (newpage) => {
  refreshtable(newpage, pageSize.value);
};

//监听page-size每页条数
const handleSizeChange = async (pagesize) => {
  refreshtable(currentPage.value, pagesize);
};
//点击修改按钮
const updateclick = (row) => {
  dialogtype.value = 1;
  dialogrole.value = true;
  nextTick(() => {
    roleform.role_name = row.role_name;
    roleform.role_remarks = row.role_remarks;
  });
  roleid.value = row.role_id;
};
//点击删除按钮
const delclick = async (row) => {
  const { data } = await delete_roleinfo(row.role_id);
  if (data.code == 200) {
    ElMessage.success(data.msg);
    refreshtable(currentPage.value, pageSize.value);
  } else {
    ElMessage.error(data.msg);
  }
};
//点击分配权限按钮
const setpowerclick = async (row) => {
  dianlogsetrole.value = true;
  //获取所有权限
  treeloading.value = true;

  const { data } = await get_rightinfo(row.role_id);
  roleid.value = row.role_id;
  if (data.code == 200) {
    rigthtred.value = data.data;
    treeRef.value!.setCheckedKeys(data.right);
    treeloading.value = false;
  }
};
//点击新增修改弹出框的确认按钮
const dialogroleclick = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      if (dialogtype.value == 0) {
        const { data } = await insert_roleinfo(roleform);
        if (data.code == 200) {
          ElMessage.success(data.msg);

          refreshtable(currentPage.value, pageSize.value);
          formEl.resetFields();
          dialogrole.value = false;
        } else {
          ElMessage.error(data.msg);
          // formEl.resetFields();
          // dialogrole.value = false;
        }
      } else {
        const { data } = await update_roleinfo(roleid.value, roleform);
        if (data.code == 200) {
          ElMessage.success(data.msg);
          formEl.resetFields();
          refreshtable(currentPage.value, pageSize.value);
          dialogrole.value = false;
        } else {
          ElMessage.error(data.msg);
          // formEl.resetFields();
        }
      }
    } else {
      console.log("验证失败");
    }
  });
};
//点击状态开关
const switchlick = async (row) => {
  roleid.value = row.role_id;
  let updatedata = {
    role_switch: row.role_switch,
  };

  const { data } = await update_roleinfo(roleid.value, updatedata);

  if (data.code == 200) {
    ElMessage.success(data.msg);
  } else {
    ElMessage.error(data.msg);
    refreshtable(currentPage.value, pageSize.value);
  }
};
//开关更新失败阻止开关
// const switchbefore = () => {
//   if (loadingswitch.value == true) {
//     loadingswitch.value = false;
//     return false;
//   } else {
//     return true;
//   }
// };

//关闭模态框之前清空表单数据
const beforeclosedialog = (done) => {
  //清空表单数据
  roleformref.value!.resetFields();
  return done(false);
};

//点击刷新按钮
const refreshclick = () => {
  refreshtable(currentPage.value, pageSize.value);
  console.log(pageSize.value);
};

//点击分配权限框的确认按钮
const rightconfirm = async () => {
  const { data } = await set_right(roleid.value, treeRef.value!.getCheckedKeys(true));
  if (data.code == 200) {
    ElMessage.success(data.msg);
    dianlogsetrole.value = false;
  } else {
    ElMessage.error(data.msg);
  }
};
</script>

<template>
  <div class="el-card_body">
    <el-form
      class="roleformclass"
      :inline="true"
      :model="roleseachform"
      label-width="80px"
    >
      <el-form-item label="角色名称:">
        <el-input v-model="roleseachform.name" placeholder="请输入角色名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search">查询</el-button>
        <el-button>重置</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="roletable"
      height="calc(100vh - 300px)"
      style="width: 100%"
    >
      <el-table-column label="Address Info">
        <template #header>
          <div class="ele-table-tool ele-table-tool-default">
            <el-button
              type="primary"
              :icon="Plus"
              @click="(dialogrole = true), (dialogtype = 0)"
              >添加</el-button
            >
            <div class="ele-tool">
              <el-tooltip effect="dark" content="刷新" placement="top">
                <el-button size="small" :icon="Refresh" @click="refreshclick"></el-button>
              </el-tooltip>

              <el-tooltip effect="dark" content="列设置" placement="top">
                <el-button size="small" :icon="Setting"></el-button>
              </el-tooltip>
            </div>
          </div>
        </template>
        <el-table-column align="center" type="index" width="50" />
        <el-table-column prop="role_name" label="角色名称" width="180" />
        <el-table-column prop="role_switch" label="状态" align="center" width="80">
          <template #default="scope">
            <el-switch
              v-model="scope.row.role_switch"
              :active-value="1"
              :inactive-value="0"
              @change="switchlick(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="role_remarks" label="备注" width="200" />
        <el-table-column prop="role_creationtime" label="创建时间" width="200" />
        <el-table-column prop="role_updatetime" label="修改时间" />
        <el-table-column fixed="right" align="center" label="操作" width="250">
          <template #default="scope">
            <el-button type="text" :icon="EditPen" @click="updateclick(scope.row)"
              >修改</el-button
            >
            <el-button type="text" :icon="Finished" @click="setpowerclick(scope.row)"
              >分配权限</el-button
            >
            <el-popconfirm @confirm="delclick(scope.row)" title="是否确认删除?">
              <template #reference>
                <el-button class="operate" type="text" :icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="ele-pagination">
      <el-pagination
        v-model:currentPage="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @update:current-page="handleCurrentChange"
        @update:page-size="handleSizeChange"
      />
    </div>
  </div>
  <!-- 角色新增和修改弹出框 -->
  <el-dialog
    :before-close="beforeclosedialog"
    :title="dialogtype == 0 ? '新增' : '修改'"
    v-model="dialogrole"
    width="25%"
  >
    <el-form ref="roleformref" :model="roleform" :rules="roleformrule" label-width="85px">
      <el-form-item label="角色名称:" prop="role_name">
        <el-input v-model="roleform.role_name"></el-input>
      </el-form-item>
      <el-form-item label="备注:" prop="role_remarks">
        <el-input type="textarea" v-model="roleform.role_remarks"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogrole = false,roleformref!.resetFields();"
          >取消</el-button
        >
        <el-button type="primary" @click="dialogroleclick(roleformref)">确认</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 分配权限弹出框 -->
  <el-dialog title="分配权限" v-model="dianlogsetrole" width="25%">
    <el-scrollbar height="50vh">
      <el-tree
        v-loading="treeloading"
        ref="treeRef"
        :data="rigthtred"
        show-checkbox
        node-key="right_id"
        default-expand-all
        :props="defaultProps"
      />
    </el-scrollbar>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dianlogsetrole = false">取消</el-button>
        <el-button type="primary" @click="rightconfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<style lang="less" scoped>
.el-card_body {
  background-color: white;
  padding: 15px;
}
.roleformclass {
  margin-bottom: 15px;
}
/deep/.roleformclass.el-form--inline .el-form-item {
  margin-right: 15px;
}
.ele-table-tool {
  display: inline-flex;
  flex-wrap: wrap;
  width: 100%;
}
.ele-tool {
  margin: 5px 0 5px auto;
}

.ele-pagination {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}
/deep/ .operate {
  color: red;
}
</style>
